﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using FacebookWrapper.ObjectModel;

namespace Desktop_Facebook
{
	public abstract class AbstractCSVSerializer
	{
		private const string k_Seperator = ",";

		public void Serialize(FileStream i_SaveFile)
		{
			List<List<string>> rows = GetRows();

			foreach (List<string> row in rows)		
			{
				appendRowToFile(i_SaveFile, row);
			}
		}

        protected abstract List<List<string>> GetRows();
		
		protected string RemoveSeperatorsFromString(string i_String)
		{
			StringBuilder builder = new StringBuilder();
			for (int i = 0; i < i_String.Length; i++)
			{
				if (i_String[i] != k_Seperator[0] && i_String[i] != '\n')
				{
					builder.Append(i_String[i]);
				}
			}

			return builder.ToString();
		}

		private void appendRowToFile(FileStream i_SaveFile, List<string> i_Row)
		{
			if (i_SaveFile == null)
			{
				throw new Exception("CSVSerializer not initalized");
			}

			foreach (string field in i_Row)
			{
				appendTextToFile(i_SaveFile, field + k_Seperator);
			}

			i_SaveFile.Seek(-1, SeekOrigin.Current);
			appendTextToFile(i_SaveFile, "\n");
		}

		private void appendTextToFile(FileStream i_FileStream, string i_Text)
		{
			Encoding hebrewEncoding = Encoding.GetEncoding("windows-1255");
			byte[] toWrite = hebrewEncoding.GetBytes(i_Text);

			i_FileStream.Write(toWrite, 0, toWrite.Length);
		}
	}
}
